import React, { useState, useEffect } from 'react';
import { Modal, Spin, Checkbox, message } from 'antd';
import PropTypes from 'prop-types';

const getCheckOptions = (array = [], fileName = {}) =>
    array.map(item => ({
        label: item[fileName.label],
        value: item[fileName.value] || item.processDefinitionId
    }));

const getDefaultValue = (array = [], fileName = {}) =>
    array.filter(item => item.checked).map(item => item[fileName.value] || item.processDefinitionId);

/**
 * 快速生成 常用流程弹出框 快捷功能弹出框
 */
const QuickCheck = props => {
    const { getData, submitData, fileName, declare, modalProps } = props;
    const user = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : {};
    const { employeeCode, firstOrgInfo } = user;
    const { onOk, visible, ...otherModalProps } = modalProps;
    const [list, setList] = useState([]);
    const [confirmLoading, setConfirmLoading] = useState(false);
    const [spinning, setSpinning] = useState(false);
    const [checkedData, setCheckedData] = useState([]);

    const validator = v => {
        if (v.length < 1) {
            message.warning('请至少可以勾选1个');
            return false;
        }
        return true;
    };

    const onChange = v => {
        if (!validator(v)) return;
        setCheckedData(v);
    };

    /**
     * 提交
     */
    const handleOk = async () => {
        const params = {};

        // 处理为数组的说明: 新旧数据处理，兼容旧的
        const arr = fileName.submitParam.split(',');
        if (arr.length > 0) {
            const oldData = list
                .filter(item => item.type !== 2)
                .map(item => item[fileName.value])
                .filter(item => !checkedData.includes(item));
            const newData = list
                .filter(item => item.type === 2)
                .map(item => item[fileName.value])
                .filter(item => !checkedData.includes(item));
            const dataArr = [oldData, newData];

            for (let i = 0; i < arr.length; i += 1) {
                params[arr[i]] = dataArr[i];
            }
        } else {
            params[fileName.submitParam] = list
                .map(item => item[fileName.value])
                .filter(item => !checkedData.includes(item));
        }

        if (!validator(checkedData)) return;

        setConfirmLoading(true);
        const response = await submitData(params);
        if (response) {
            onOk();
        }
        setConfirmLoading(false);
    };

    useEffect(() => {
        const fetchList = async () => {
            setSpinning(true);
            const params = {
                employeeCode,
                companyCode: firstOrgInfo?.firstCompanyCode
            };
            const response = await getData(params);
            setSpinning(false);
            if (response && response.code === 10000) {
                const dataList = response.data;
                // 新流程 type === 2
                const newList = dataList.map(item => {
                    if (item.type === 2) {
                        return { ...item, templateId: item.processDefinitionId };
                    }
                    return item;
                });
                setList(newList);
                setCheckedData(getDefaultValue(response.data, fileName));
            }
        };
        if (visible) {
            fetchList();
        }
    }, [visible]);
    return (
        <Modal
            id="quickCheck"
            onOk={handleOk}
            confirmLoading={confirmLoading}
            destroyOnClose
            visible={visible}
            okText="提交"
            {...otherModalProps}
        >
            <Spin spinning={spinning}>
                <div
                    style={{
                        fontSize: '14px',
                        lineHeight: '22px',
                        marginBottom: '19px'
                    }}
                >
                    {declare}
                </div>
                <Checkbox.Group options={getCheckOptions(list, fileName)} value={checkedData} onChange={onChange} />
            </Spin>
        </Modal>
    );
};
QuickCheck.propTypes = {
    getData: PropTypes.func.isRequired,
    submitData: PropTypes.func.isRequired,
    // onOk: PropTypes.func.isRequired,
    // visible: PropTypes.bool.isRequired,
    // title: PropTypes.string.isRequired,
    fileName: PropTypes.shape({
        label: PropTypes.string.isRequired,
        value: PropTypes.string,
        defaultValue: PropTypes.string.isRequired,
        submitParams: PropTypes.string
    })
};
QuickCheck.defaultProps = {
    fileName: {
        label: 'menuName',
        value: 'menuId',
        defaultValue: 'selfId',
        submitParams: 'menuId'
    }
};
export default QuickCheck;
